import { loginApi } from '@/api/login'
import { getUserInfo } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {},
      menuList: [...constantRoutes]
    }
  },
  mutations: {
    SET_TOKEN(state, token) {
      setToken(token)
      state.token = token
    },
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
      state.userInfo = {}
    },
    SET_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
    REMOVE_USERINFO(state) {
      state.userInfo = {}
    },
    SET_MENULIST(state, newRoutes) {
      state.menuList = [...state.menuList, ...newRoutes]
    },
    resetMenu(state) {
      state.menuList = [...constantRoutes]
      resetRouter()
    }
  },
  actions: {
    async login(context, data) {
      const res = await loginApi(data)
      context.commit('SET_TOKEN', res.data.token)
      Message.success('登录成功')
      router.replace('/')
    },
    logout(context) {
      context.commit('REMOVE_TOKEN')
      context.commit('REMOVE_USERINFO')
      context.commit('resetMenu')
    },
    async getUserInfo(context) {
      const res = await getUserInfo()
      context.commit('SET_USERINFO', res.data)
      return res.data.permissions
    }
  }
}
